// 游戏常量
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const COLORS = [
  null,
  '#FF0D72',
  '#0DC2FF',
  '#0DFF72',
  '#F538FF',
  '#FF8E0D',
  '#FFE138',
  '#3877FF'
];

// 方块形状
const SHAPES = [
  [0, 0, 0, 0],
  [0, 1, 1, 0, 0, 1, 1, 0], // O
  [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], // L
  [0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0], // J
  [0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], // T
  [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0], // S
  [0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], // Z
  [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0] // I
];

// 游戏状态
let canvas = document.getElementById('tetris');
let ctx = canvas.getContext('2d');
let scoreDisplay = document.getElementById('score-display');
let startButton = document.getElementById('start-button');
let score = 0;
let board = createMatrix(COLS, ROWS);
let piece = null;
let nextPiece = null;
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
let isPlaying = false;
let gameOver = false;
let restartButton = null;

// 初始化游戏
function init() {
  board = createMatrix(COLS, ROWS);
  score = 0;
  gameOver = false;
  createPiece();
  updateScore();
  window.requestAnimationFrame(gameLoop);
  
  if (restartButton) {
    restartButton.style.display = 'none';
  }
}

// 游戏主循环
function gameLoop(time = 0) {
  if (gameOver) return;
  
  const deltaTime = time - lastTime;
  lastTime = time;
  
  dropCounter += deltaTime;
  if (dropCounter > dropInterval) {
    movePieceDown();
    dropCounter = 0;
  }
  
  draw();
  window.requestAnimationFrame(gameLoop);
}

// 绘制游戏
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制背景
  ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 绘制已落下的方块
  drawMatrix(board, {x: 0, y: 0});
  
  // 绘制当前方块
  if (piece) {
    drawMatrix(piece.matrix, piece.pos);
  }
  
  // 绘制预览方块
  if (nextPiece) {
    const previewCanvas = document.getElementById('preview');
    const previewCtx = previewCanvas.getContext('2d');
    previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
    // 绘制背景
    previewCtx.fillStyle = 'rgba(101, 239, 16, 0.3)'; 
console.log(nextPiece)
    drawMatrix(nextPiece.matrix, {x: 0, y: 0}, previewCtx);
  }
}

// 创建新方块
function createPiece() {
  const shapeId = nextPiece ? nextPiece.shapeId : Math.floor(Math.random() * (SHAPES.length - 1)) + 1;
  const nextShapeId = Math.floor(Math.random() * (SHAPES.length - 1)) + 1;
  
  const matrix = createMatrix(4, 4);
  const nextMatrix = createMatrix(4, 4);
  
  for (let y = 0; y < 4; y++) {
    for (let x = 0; x < 4; x++) {
      if (SHAPES[shapeId][y * 4 + x]) {
        matrix[y][x] = shapeId;
      }
      if (SHAPES[nextShapeId][y * 4 + x]) {
        nextMatrix[y][x] = nextShapeId;
      }
    }
  }
  
  piece = {
    matrix: matrix,
    pos: {x: Math.floor(COLS / 2) - 2, y: 0},
    shapeId: shapeId
  };
  
  nextPiece = {
    matrix: nextMatrix,
    shapeId: nextShapeId
  };
}

// 方块旋转
function rotatePiece(direction) {
  if (gameOver) return;
  
  // 正方形方块不需要旋转
  if (piece.shapeId === 1) return;
  
  const matrix = piece.matrix;
  const N = matrix.length;
  const rotated = createMatrix(N, N);
  
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      if (direction === 'right') {
        rotated[x][N - 1 - y] = matrix[y][x];
      } else {
        rotated[N - 1 - x][y] = matrix[y][x];
      }
    }
  }
  
  // 临时保存当前矩阵和位置
  const originalMatrix = piece.matrix;
  const originalPos = {...piece.pos};
  
  // 应用旋转并检查碰撞
  piece.matrix = rotated;
  if (collide()) {
    // 如果有碰撞则恢复原状
    piece.matrix = originalMatrix;
    piece.pos = originalPos;
    return;
  }
}

// 方块移动
function movePieceDown() {
  if (gameOver) return;
  
  piece.pos.y++;
  if (collide()) {
    piece.pos.y--;
    merge();
    clearLines();
    
    // 检查游戏是否结束
    if (piece.pos.y === 0) {
      gameOver = true;
      showGameOver();
      return;
    }
    
    createPiece();
  }
}

function movePieceLeft() {
  piece.pos.x--;
  if (collide()) {
    piece.pos.x++;
  }
}

function movePieceRight() {
  piece.pos.x++;
  if (collide()) {
    piece.pos.x--;
  }
}

// 碰撞检测
function collide() {
  const [m, o] = [piece.matrix, piece.pos];
  for (let y = 0; y < m.length; y++) {
    for (let x = 0; x < m[y].length; x++) {
      if (m[y][x] !== 0 &&
          (board[y + o.y] && board[y + o.y][x + o.x]) !== 0) {
        return true;
      }
    }
  }
  return false;
}

// 合并方块到棋盘
function merge() {
  piece.matrix.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value !== 0) {
        board[y + piece.pos.y][x + piece.pos.x] = value;
      }
    });
  });
}

// 清除已填满的行
function clearLines() {
  let linesCleared = 0;
  
  outer: for (let y = ROWS - 1; y >= 0; y--) {
    for (let x = 0; x < COLS; x++) {
      if (board[y][x] === 0) {
        continue outer;
      }
    }
    
    const row = board.splice(y, 1)[0].fill(0);
    board.unshift(row);
    linesCleared++;
    y++;
  }
  
  if (linesCleared > 0) {
    score += linesCleared * 100;
    updateScore();
  }
}

// 更新分数显示
function updateScore() {
  scoreDisplay.textContent = `分数: ${score}`;
}

function showGameOver() {
  if (!restartButton) {
    restartButton = document.createElement('button');
    restartButton.id = 'restart-button';
    restartButton.textContent = '再来一局';
    restartButton.style.position = 'absolute';
    restartButton.style.top = '60%';
    restartButton.style.left = '50%';
    restartButton.style.transform = 'translate(-50%, -50%)';
    restartButton.style.padding = '10px 20px';
    restartButton.style.fontSize = '18px';
    restartButton.style.backgroundColor = '#4CAF50';
    restartButton.style.color = 'white';
    restartButton.style.border = 'none';
    restartButton.style.borderRadius = '5px';
    restartButton.style.cursor = 'pointer';
    restartButton.onclick = init;
    
    document.getElementById('game-container').appendChild(restartButton);
  }
  
  restartButton.style.display = 'block';
  
  const gameOverText = document.createElement('div');
  gameOverText.id = 'game-over-text';
  gameOverText.textContent = '游戏结束!';
  gameOverText.style.position = 'absolute';
  gameOverText.style.top = '40%';
  gameOverText.style.left = '50%';
  gameOverText.style.transform = 'translate(-50%, -50%)';
  gameOverText.style.fontSize = '24px';
  gameOverText.style.color = '#FF0D72';
  gameOverText.style.fontWeight = 'bold';
  gameOverText.style.textShadow = '0 0 5px rgba(255, 255, 255, 0.5)';
  
  document.getElementById('game-container').appendChild(gameOverText);
  
  setTimeout(() => {
    document.getElementById('game-container').removeChild(gameOverText);
  }, 2000);
}

// 辅助函数
function createMatrix(w, h) {
  const matrix = [];
  while (h--) {
    matrix.push(new Array(w).fill(0));
  }
  return matrix;
}

function drawMatrix(matrix, offset, ctx = canvas.getContext('2d')) {
  const blockSize = BLOCK_SIZE;
  if (ctx !== canvas.getContext('2d')) {
    ctx.setTransform(1, 0, 0, 1, 0, 0); // 重置变换矩阵
    // 计算预览方块居中位置
    const previewWidth = ctx.canvas.width;
    const previewHeight = ctx.canvas.height;
    const matrixWidth = matrix[0].length * blockSize;
    const matrixHeight = matrix.length * blockSize;
    offset = {
      x: (previewWidth - matrixWidth) / 2 / blockSize,
      y: (previewHeight - matrixHeight) / 2 / blockSize
    };
    console.log(offset)
  }
  
  matrix.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value !== 0) {
        ctx.fillStyle = COLORS[value];
        ctx.fillRect(
          (x + offset.x) * blockSize,
          (y + offset.y) * blockSize,
          blockSize,
          blockSize
        );
        
        // 添加方块边框效果
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
        ctx.lineWidth = 2;
        ctx.strokeRect(
          (x + offset.x) * blockSize,
          (y + offset.y) * blockSize,
          blockSize,
          blockSize
        );
      }
    });
  });
}

// 键盘控制
document.addEventListener('keydown', event => {
  if (!piece) return;
  
  switch (event.keyCode) {
    case 37: // 左箭头
      movePieceLeft();
      break;
    case 39: // 右箭头
      movePieceRight();
      break;
    case 40: // 下箭头
      movePieceDown();
      break;
    case 38: // 上箭头 - 顺时针旋转
      rotatePiece('right');
      break;
    case 90: // Z键 - 逆时针旋转
      rotatePiece('left');
      break;
  }
});

// 开始按钮点击事件
startButton.addEventListener('click', () => {
  if (!isPlaying) {
    isPlaying = true;
    startButton.style.display = 'none';
    init();
  }
});